package io.gitee.cofenghen.jdbctempleplus.core;

import io.gitee.cofenghen.jdbctempleplus.BaseJdbcTemplePlus;
import io.gitee.cofenghen.jdbctempleplus.exception.OrmException;
import io.gitee.cofenghen.jdbctempleplus.support.QueryCondition;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class BaseRepository <T> implements Repository<T> {
    @Autowired
    private OrmTemplate ormTemplate;
    private Class<T> entityClass;

    public BaseRepository() {
       // this.ormTemplate = ormTemplate;
        // 通过反射获取泛型的实际类型
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length > 0) {
                this.entityClass = (Class<T>) actualTypeArguments[0];
            }
        }
        if (entityClass == null) {
            throw new IllegalArgumentException("无法确定实体类类型");
        }
    }
    @Override
    public BaseJdbcTemplePlus ado() {
        return ormTemplate.ado();
    }

    @Override
    public <T> int insert(T entity) throws OrmException {
        return this.ormTemplate.insert(entity);
    }

    @Override
    public <T> int batchInsert(List<T> entities) throws OrmException {
        return this.ormTemplate.batchInsert(entities);
    }

    @Override
    public  T queryById( Object id) throws OrmException {
        return this.ormTemplate.queryById(entityClass,id);
    }

    @Override
    public  List<T> query( QueryCondition<T> queryCondition) {
        return this.ormTemplate.query(entityClass,queryCondition);
    }

    @Override
    public <T> int updateById(Object id, T entity) {
        return this.ormTemplate.updateById(id,entity);
    }

    @Override
    public  int deleteById( Object id) {
        return this.ormTemplate.deleteById(entityClass,id);
    }
}
